package com.demo.demo.images;

import com.google.common.collect.Lists;
import lombok.experimental.var;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

/**
 * Copyright
 *
 * @Author WuHuang
 * @Date 2023/5/23
 */
public class MergeImages3 {
//        public static void main(String[] args) {
//        try {
//            // Load the input image
//            URL url = new URL("https://sh-staging-changyi-wecom20-01.oss-cn-shanghai.aliyuncs.com/2023/05/17/4a81f8a8-4c0a-453c-9fe5-7fbc1e0a149e.png");
//            // Convert multipartFile to File
////            MultipartFile multipartFile = null;// get the uploaded file from frontend
////            File file = new File(multipartFile.getOriginalFilename());
////            multipartFile.transferTo(file);
//
//            BufferedImage inputImage = ImageIO.read(url);
//            // Create a graphics object for the input image
//            Graphics2D g = inputImage.createGraphics();
//
//            // Set the font and color for the price text
////            Font font = new Font("宋体", Font.BOLD, 24);//默认 24
//
//            Font font = new Font("PingFang SC", Font.BOLD, 62);
//            Font font2 = new Font("PingFang SC", Font.BOLD, 58);
//
//            Color textColor1 = Color.WHITE;
//            Color textColor2 = Color.BLACK;
//            Color bgColor = new Color(217, 0, 27);
//            Color bgColor2 = new Color(255, 255, 255);
//            g.setFont(font);
//
//            // Draw the first price label with red background at top right corner
//            String price1 = "活动价: ¥102.99";
//            //横坐标
//            int x1 = inputImage.getWidth() - g.getFontMetrics().stringWidth(price1) - 20;
//            //纵坐标
//            int y1 = 90;
//            //标签的宽度
//            int width = 600;
//            int height = 217;
//            g.setColor(bgColor);
//            g.fillRect(x1, 0, width, height);
//            g.setColor(textColor1);
//            g.drawString(price1, x1 + 5, y1 - 3);
//
//            // Draw the second price label with strike-through effect at top right corner
//            g.setFont(font2);
//            String price2 = "吊牌价: ¥122.99";
//            //横坐标
//            int x2 = x1;
//            //纵坐标
//            int y2 = y1 + 50;
////            g.setColor(bgColor2);
////            g.fillRect(x2 - 18, y2 - 40, width, height);
//            g.setColor(textColor2);
//            g.drawString(price2 , x2 + 5, y2 - 3);
//            g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
//            g.drawLine(x2 - 10, y2 - 10, x2 + g.getFontMetrics().stringWidth(price2) + 5, y2 - 20);
//
//            // Save the modified image to a file
//            ImageIO.write(inputImage, "png", new File("D:\\WorkSpace\\wu\\spring-boot-study\\springboot-demo\\src\\main\\resources\\output10.jpg"));
//            // Dispose of the graphics object
//            g.dispose();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

    public static void main(String[] args) throws IOException {
        mergeMaterialImage("https://sh-staging-changyi-wecom20-01.oss-cn-shanghai.aliyuncs.com/2023/05/17/4a81f8a8-4c0a-453c-9fe5-7fbc1e0a149e.png"
                , "1330.00", "1080.00", "测试一下测试一下测试一下测试一下测试一下测试一下测试一下测试一下测试一下测试一下");
    }

    public static void mergeMaterialImage(String originalUrl, String originalPrice, String promotionPrice, String styleName) throws IOException {
        // 读取原始图片
        URL url = new URL(originalUrl);
        URLConnection urlConnection = url.openConnection();
        urlConnection.setConnectTimeout(3000); // 设置连接超时时间为2秒
        urlConnection.setReadTimeout(3000); // 设置读取数据超时时间为2秒
        BufferedImage image = ImageIO.read(urlConnection.getInputStream());

        // Get the graphics context for the image
        Graphics2D g2d = image.createGraphics();

        // Add a red label with price in the top right corner
        Color bgColor = new Color(201, 16, 47);
        g2d.setColor(bgColor);
        g2d.fillRect(image.getWidth() - 600, 0, 600, 217);
        g2d.setColor(Color.WHITE);
        g2d.setFont(new Font("PingFang SC", Font.BOLD, 62));
        g2d.drawString("优惠价: ¥" + promotionPrice, image.getWidth() - 550, 130);

        // Add a transparent label with price below the red label
        g2d.setColor(Color.BLACK);
        g2d.setFont(new Font("PingFang SC", Font.BOLD, 58));
        int stringWidth = g2d.getFontMetrics().stringWidth(originalPrice);
        g2d.drawString("原价: ¥" + originalPrice, image.getWidth() - 480, 315);
        g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
        // 修改直线的起点和终点，使其与字符串的长度匹配
        int startX = image.getWidth() - 300; // 起点横坐标为字符串的起点横坐标
        int endX = startX + stringWidth; // 终点横坐标为字符串的终点横坐标
        // 创建一个新的Stroke对象，设置线条宽度为4个像素
        Stroke stroke = new BasicStroke(6);
        // 设置画笔的Stroke属性
        g2d.setStroke(stroke);
        g2d.drawLine(startX , 300, endX , 300); // 使用新的起点和终点横坐标
//        g2d.drawLine(image.getWidth() - 300, 300, image.getWidth() - 100, 300);

//        mergerImagesv2(g2d,image,styleName,null);
        mergerImagesv2(g2d,image,styleName,null);
        // 保存修改后的图片

        File outputFile = new File("D:\\WorkSpace\\wu\\spring-boot-study\\springboot-demo\\src\\main\\resources\\output10.png");
        ImageIO.write(image, "png", outputFile);
    }

    /**
     * 只截取一行
     * @param g
     * @param image2
     * @param labelText
     * @param file
     */
    private static void mergerImages(Graphics2D g, BufferedImage image2, String labelText, File file) {
        int labelWidth = 1800;
        int labelHeight = 320;
        int labelX = (image2.getWidth() - labelWidth) / 2;
        int labelY = (image2.getHeight() - labelHeight);
        g.setColor(new Color(0, 0, 0, 128));
        g.fillRect(0, labelY, labelWidth, labelHeight);
        // Add the label text to the new image
        g.setColor(Color.WHITE);
//        g.setFont(new Font("宋体", Font.BOLD, 106));
        g.setFont(new Font("PingFang SC", Font.BOLD, 106));
        int maxLabelWidth = labelWidth - 40; // 剩余空间最多容纳的字符宽度
        int stringWidth = g.getFontMetrics().stringWidth(labelText); // 字符串宽度
        if (stringWidth > maxLabelWidth) {
            char[] chars = labelText.toCharArray();
            int endIndex = 0;
            int sumWidth = 0;
            for (int i = 0; i < chars.length; i++) {
                char c = chars[i];
                if (c >= '\u4e00' && c <= '\u9fa5') { // 判断是否为汉字
                    sumWidth += g.getFontMetrics().charsWidth(chars, i, 1);
                    if (sumWidth > maxLabelWidth) {
                        endIndex = i - 1;
                        break;
                    }
                } else {
                    sumWidth += g.getFontMetrics().charWidth(c);
                    if (sumWidth > maxLabelWidth) {
                        endIndex = i - 1;
                        break;
                    }
                }
                endIndex = i;
            }
            labelText = labelText.substring(0, endIndex + 1);
        }
        int x = labelX + (labelWidth - g.getFontMetrics().stringWidth(labelText)) / 2;
        int y = labelY + ((labelHeight - g.getFontMetrics().getHeight()) / 2) + g.getFontMetrics().getAscent();
        g.drawString(labelText, x, y);
    }

    /**
     *  labelText 超过两行的换行处理，最后两行
     * @param g2d
     * @param image
     * @param labelText
     * @param file
     */
    private static void mergerImagesv2(Graphics2D g2d, BufferedImage image, String labelText, File file) {
        // 在新图像的中心填充一个半透明的黑色矩形
        int labelWidth = 1800;
        int labelHeight = 320;
        int labelX = (image.getWidth() - labelWidth) / 2;
        int labelY = (image.getHeight() - labelHeight);
        g2d.setColor(new Color(0, 0, 0, 128));
        g2d.fillRect(0, labelY, labelWidth, labelHeight);
        // Add the label text to the new image
        g2d.setColor(Color.WHITE);
        g2d.setFont(new Font("PingFang SC", Font.BOLD, 106));

        FontMetrics fontMetrics = g2d.getFontMetrics();
        int maxLabelWidth = labelWidth - 40; // 剩余空间最多容纳的字符宽度
        if (fontMetrics.stringWidth(labelText) > maxLabelWidth) {
            ArrayList<String> lines = new ArrayList<>();
            StringBuilder line = new StringBuilder();
            for (char c : labelText.toCharArray()) {
                int lineWidth = fontMetrics.stringWidth(line.toString() + c);
                if (lineWidth > maxLabelWidth) {
                    lines.add(line.toString());
                    if (lines.size() >= 1){
                        line.setLength(0);
                        break;
                    }
                    line = new StringBuilder(String.valueOf(c));
                } else {
                    line.append(c);
                }
            }
            if (line.length() > 0) {
                lines.add(line.toString());
            }
            int lineHeight = fontMetrics.getHeight();
            int y = labelY + ((labelHeight - lineHeight * lines.size()) / 2) + fontMetrics.getAscent();
            for (String lineText : lines) {
                int lineWidth = fontMetrics.stringWidth(lineText);
                int x = labelX + (labelWidth - lineWidth) / 2;
                g2d.drawString(lineText, x, y);
                y += lineHeight;
            }
        } else {
            int x = labelX + (labelWidth - fontMetrics.stringWidth(labelText)) / 2;
            int y = labelY + ((labelHeight - fontMetrics.getHeight()) / 2) + fontMetrics.getAscent();
            g2d.drawString(labelText, x, y);
        }
    }


    private static void addPriceTag(Graphics2D g, String text, int x, int y, Font font, Color color, boolean addShadow) {
        FontMetrics fm = g.getFontMetrics(font);
        int textWidth = fm.stringWidth(text);
        int labelHeight = fm.getHeight();
        // 设置字体和颜色
        g.setFont(font);
        g.setColor(color);

        // 添加阴影
        if (addShadow) {
            g.setColor(new Color(0, 0, 0, 0)); // 完全透明
            for (int i = -2; i <= 2; i++) {
                for (int j = -2; j <= 2; j++) {
                    if (i != 0 || j != 0) {
                        g.drawString(text, x + i, y + j);
                    }
                }
            }
        }

        // 添加文字
        g.setColor(color);
        g.drawString(text, x, y + labelHeight);
    }
}
